package org.example.course.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.commonapi.domain.*;
import org.example.commonapi.dto.CourseStudentDto;
import org.example.commonapi.dto.LoginInfo;
import org.example.commonapi.util.JwtUtil;
import org.example.commonapi.util.options.ChoiceOptionsService;
import org.example.course.service.CourseExamsService;
import org.example.course.service.ExamQuestionsService;
import org.example.course.service.StudentExamService;
import org.example.course.until.CourseUntil;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static org.example.commonapi.domain.Constants.Assignment_TYPE;
import static org.example.commonapi.domain.Constants.Exam_TYPE;

@RestController
@RequestMapping("/course")
@Slf4j
public class CourseExamsController {

    @Resource
    private CourseExamsService courseExamsService;

    @Resource
    private ChoiceOptionsService choiceOptionsService;

    @Resource
    private ExamQuestionsService examQuestionsService;

    @Resource
    private CourseUntil courseUntil;

    @Resource
    private StudentExamService studentExamService;

    @Resource
    private JwtUtil jwtUtil;

    /**
     * 查询课程考试信息（不需要他，我需要把题目分开）
     * @param courseId
     * @return
     */
    @GetMapping("/list/allexams/{courseId}")
    public R listCourseExams(@PathVariable("courseId") Long courseId) {
        LambdaQueryWrapper<CourseExams> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseExams::getCourseId, courseId);
        List<CourseExams> list = courseExamsService.list(queryWrapper);
        log.info("该课程考试有:{}",list);
        return R.success(list);
    }

    /**
     * 查询进行中的考试
     * @param courseId
     * @return
     */
    @GetMapping("/list/ongoing/exams/{courseId}")
    public R listOngoingExams(@PathVariable("courseId") Long courseId) {
        LocalDateTime  now= LocalDateTime.now();
        LambdaQueryWrapper<CourseExams> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseExams::getCourseId, courseId)
                .le(CourseExams::getStartTime, now)
                .ge(CourseExams::getEndTime, now);
        List<CourseExams> list = courseExamsService.list(queryWrapper);
        log.info("该课程进行中考试有:{}",list);
        return R.success(list);
    }

    /**
     * 查询已经结束的考试
     * @param courseId
     * @return
     */
    @GetMapping("/list/end/exams/{courseId}")
    public R listFinishedExams(@PathVariable("courseId") Long courseId) {
        LocalDateTime  now= LocalDateTime.now();
        LambdaQueryWrapper<CourseExams> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseExams::getCourseId, courseId)
                .lt(CourseExams::getEndTime, now);
        List<CourseExams> list = courseExamsService.list(queryWrapper);
        log.info("该课程已经结束考试有:{}",list);
        return R.success(list);
    }

    /**
     * 新增课程考试
     * @param courseExams
     * @return
     */
    @PostMapping("/insert/exams")
    public R addCourseExams(@RequestBody CourseExams courseExams) {
        R result= CourseUntil.isCourseExams(courseExams);
        if(result!=null)return result;
        courseExams.setCreateTime(LocalDateTime.now());
        courseExamsService.save(courseExams);
//        给所有学生发送到收件箱
//        courseUntil.insertInbox(courseExams.getCourseId(),courseExams.getName(),courseExams.getId()
//                ,Exam_TYPE,courseExams.getCreateTime(),courseExams.getEndTime());

        log.info("新增课程考试成功{}",courseExams);
        return R.success(courseExams.getId());
    }
    /**
     * 修改课程考试
     * @param courseExams
     * @return
     */
    @PutMapping("/update/exams")
    public R updateCourseExams(@RequestBody CourseExams courseExams) {
        // 检查课程考试信息是否合法
        R result= CourseUntil.isCourseExams(courseExams);
        if(result!=null)return result;
        courseExamsService.updateById(courseExams);
        log.info("修改课程考试成功{}",courseExams);
        return R.success();
    }

    /**
     * 删除课程考试
     * @param id
     * @return
     */
    @DeleteMapping("/delete/exams/{id}")
    public R deleteCourseExams(@PathVariable("id") Integer id) {
        courseExamsService.removeById(id);
        log.info("删除课程考试成功{}",id);
        return R.success();
    }


    /**
     * 查询课程考试信息
     * @param id
     * @return
     */
    @GetMapping("/get/exams/{id}")
    public R getCourseExams(@PathVariable("id") Integer id) {
        CourseExams courseExams=courseExamsService.getById(id);
        log.info("查询课程考试成功{}",courseExams);
        return R.success(courseExams);
    }

    /**
     * 查询课程考试题目
     * @param examId
     * @return
     */
    @GetMapping("/list/exams/questions/{examId}")
    public R listCourseExamsQuestion(@PathVariable("examId") Long examId) {
        LambdaQueryWrapper<ExamQuestions> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExamQuestions::getExamId, examId);
        List<ExamQuestions> list = examQuestionsService.list(queryWrapper);
        log.info("该课程考试有:{}",list);
        return R.success(list);
    }


    /**
     * 查询课程考试题目选项
     * @param id
     * @return
     */
    @GetMapping("/get/exams/question/options/{id}")
    public R getCourseExamsQuestionOptions(@PathVariable("id") Long id) {
        LambdaQueryWrapper<ChoiceOptions> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChoiceOptions::getExamQuestionId, id);
        ChoiceOptions choiceOptions = choiceOptionsService.getOne(queryWrapper);
        log.info("查询课程考试题目选项成功{}",choiceOptions);
        return R.success(choiceOptions);
    }


    /**
     * 新增课程考试题目
     * @param id
     * @param examQuestionList
     * @return
     */
    @PostMapping("/insert/list/exams/questions/{id}")
    public R addCourseExamsQuestion(@PathVariable("id") Long id,@RequestBody List<ExamQuestions> examQuestionList) {
        for(ExamQuestions examQuestions:examQuestionList){
            examQuestions.setExamId(id);
        }
        examQuestionsService.saveBatch(examQuestionList);
        List<Long> ids=examQuestionList.stream().map(ExamQuestions::getId).collect(Collectors.toList());
        log.info("新增课程考试题目成功{}",examQuestionList);
        return R.success(ids);
    }

    /**
     * 新增课程考试题目选项
     * @param choiceOptionsList
     * @return
     */
    @PostMapping("/insert/list/exams/questions/options")
    public R addCourseExamsQuestionOptions(@RequestBody List<ChoiceOptions> choiceOptionsList) {
        choiceOptionsService.saveBatch(choiceOptionsList);
        log.info("新增课程考试题目选项成功{}",choiceOptionsList);
        return R.success();
    }

    /**
     * todo 课程考试提交答案
     * @param answer
     * @param id
     * @return
     */
    @PostMapping("/post/exams/submitAnswer")
    public R<String> submitAnswer(@RequestParam("answer") String answer, @RequestParam("id") Integer id)  {
//        ai判题直接给分
        return examQuestionsService.submitAnswer(answer,id);
    }

    /**
     * 学生课程考试提交
     * @param examId
     * @param request
     * @return
     */
    @PostMapping("/submit/exams/{examId}")
    public R submitExams(@PathVariable Long examId, HttpServletRequest request) {
        LoginInfo loginInfo = jwtUtil.parseJwt(request.getHeader("token"));
        StudentExam studentExam = new StudentExam();
        studentExam.setStudentId(loginInfo.getId());
        studentExam.setExamId(examId);
        studentExamService.save(studentExam);
        return R.success();
    }

    /**
     * 查询学生是否已经考试过了
     */
    @GetMapping("/get/exams/finish/{examId}")
    public R getStudentExamFinish(@PathVariable Long examId,HttpServletRequest request) {
        LoginInfo loginInfo = jwtUtil.parseJwt(request.getHeader("token"));
        LambdaQueryWrapper<StudentExam> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentExam::getExamId,examId).eq(StudentExam::getStudentId,loginInfo.getId());
        boolean studentExam = studentExamService.exists(queryWrapper);
        return R.success(studentExam);
    }

}
